/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import React, { useRef, useState, useEffect } from 'react';
import { BreakpointManager } from '@hadss/web_adaptive_layout_ui';
import { getBreakpointsAttr, getbreakpointManager } from '../../utils/getBreakpoint';
import { getScopeId } from '../../utils/getScopeId';
import { GridColProps } from '../../types/multiGridRowCol';

declare global {
  namespace JSX {
    interface IntrinsicElements {
      'grid-col': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> & {
        name?: string | number;
        span?: string | number | object;
        offset?: string | number | object;
        order?: string | number | object;
        label?: string;
        icon?: string;
        scope?: string;
        class?: string;
      }
    }
  }
}

export const MultiGridCol: React.FC<GridColProps> = (props) => {
  const scopeId = useRef<string>(getScopeId());
  const propsRef = useRef(props);
  const [span, setSpan] = useState(undefined);
  const [offset, setOffset] = useState(undefined);
  const [order, setOrder] = useState(undefined);
  const breakpointManager = useRef<BreakpointManager>(null);
  const unsubscribe = useRef<Function>(() => {});
  const parentElement = useRef<HTMLElement | null>(null);

  const getCurrentAttr = () => {
    if (propsRef.current.span !== undefined) {
      setSpan(getBreakpointsAttr(propsRef.current.span, breakpointManager.current));
    }
    if (propsRef.current.offset !== undefined) {
      setOffset(getBreakpointsAttr(propsRef.current.offset, breakpointManager.current));
    }
    if (propsRef.current.order !== undefined) {
      setOrder(getBreakpointsAttr(propsRef.current.order, breakpointManager.current));
    }
  };

  useEffect(() => {
    propsRef.current = props;
    if (breakpointManager.current) {
      getCurrentAttr();
    }
  }, [props]);

  const subscribeBreakpoint = () => {
    if (parentElement.current) {
      const breakpointValue = JSON.parse(parentElement.current.getAttribute('breakpointvalue') || '');
      const breakpointRefrence = parentElement.current.getAttribute('breakpointrefrence');
      breakpointManager.current = getbreakpointManager(
        breakpointRefrence,
        breakpointValue,
        parentElement.current.getAttribute('scope') || ''
      );
      unsubscribe.current = breakpointManager.current.subscribeToBreakpoint(() => {
        getCurrentAttr();
      });
    }
  };

  useEffect(() => {
    parentElement.current = document.querySelector(`.${scopeId.current}`)?.parentElement as HTMLElement;
    parentElement.current.addEventListener('gridRowReactMounted', subscribeBreakpoint);

    return () => {
      unsubscribe.current();
      if (breakpointManager.current) {
        breakpointManager.current.destroy();
      }
      parentElement.current?.removeEventListener('gridRowReactMounted', subscribeBreakpoint);
    }
  }, []);

  return (
    <grid-col
      name={props.name}
      scope={scopeId.current}
      class={`${scopeId.current} ${props.className}`}
      span={span}
      offset={offset}
      order={order}
      label={props.label}
      icon={props.icon}
      >
      {props.children}
    </grid-col>
  )
};

MultiGridCol.displayName = 'MultiGridCol';